import {Module} from 'vuex';
import {cookieUtil} from '@/util/Cookie';
import buildConfig from '@/util/CommonParam';
import {User} from '@/model/UserClass';

export class UserState {
  public user!: User | null;
  public permissionNames!: string[];
  get token(): string | null {
    return cookieUtil.get(buildConfig.tokenKey);
  }

  set token(value: string | null) {
    cookieUtil.set(buildConfig.tokenKey, value, 30);
  }
}
export let user: Module<UserState, any> = {
  namespaced: true,
  state: new UserState(),
  getters: {
    token: (state) => state.token,
    user: (state) => state.user,
    permissions: (state) => state.permissionNames,
  },
  mutations: {
    setToken: (state, payload: string) => state.token = payload,
    setUser: (state, payload: User) => state.user = payload,
    setPermissions: (state, payload: string[]) => state.permissionNames = payload,
  },
  actions: {
    asyncSetToken: (context, payload: string) => context.commit('setToken', payload),
    asyncSetUser: (context, payload: User) => context.commit('setUser', payload),
    asyncSetPermission: (context, payload: string[]) => context.commit('setPermissions', payload),
  },
};

